package gui;

import business.EventManager;
import business.Notifier;
import business.UserManager;
import entity.Event;
import entity.User;
import java.io.IOException;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

@Named(value = "miniEventBean")
@RequestScoped
public class MiniEventBean {

    private int eventId;

    @EJB
    private EventManager eventManager;
    @EJB
    private UserManager userManager;

    public MiniEventBean() {
    }

    @PostConstruct
    public void loadEvent() {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        String eventKey = "";
        for (String key : context.getRequestParameterMap().keySet()) {
            if (key.endsWith("eventId")) {
                eventKey = key;
            }
        }
        String id = context.getRequestParameterMap().get(eventKey);
        if (id != null) {
            eventId = Integer.parseInt(id);
        }
    }

    public String delete() throws IOException {
        Event event = eventManager.find(eventId);
        if (event != null) {
            eventManager.delete(event);
        }
        return "";
    }

    public String cancelParticipation() {
        User currentUser = userManager.getLoggedUser();
        Event event = eventManager.find(eventId);
        if (event != null) {
            event.removeParticipant(currentUser);
            currentUser.getCalendars().get(0).removeEvent(event);
            userManager.save(currentUser);
            eventManager.save(event);
        }
        return "";
    }
}
